package cn.pconline.autoclub.web;

import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.passport2.Account;
import cn.pconline.passport2.Passport;
import cn.pconline.passport2.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 登录拦截器 如果是进入后台，根据是否登录后台来判断跳转
 */
public class UserInterceptor extends HandlerInterceptorAdapter {

    private Passport passport;
    @Autowired
    private UserService userService;
    @Autowired
    private MemberService memberService;

    public void setPassport(Passport passport) {
        this.passport = passport;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getAttribute("user");
        if (user == null) {
            Session session = passport.recognize(request, response);
            if (session != null) {
                user = userService.findUser(session.getAccountId());
                if (user == null) {
                    user = new User();
                    Account account = passport.getAccount(session.getAccountId());
                    user.setUid(account.getAccountId());
                    user.setUsername(account.getAccountName());
                    user.setCreateAt(DateUtils.getNow());
                    userService.createUser(user);
                }
            } else {
                user = User.ANONYMOUS;
            }
            request.setAttribute("user", user);

            long clubId = NumberUtils.toLong(request.getParameter("clubId"));
            if (clubId > 0) {
                ClubMember member = memberService.findMember(user.getUid(), clubId);
                request.setAttribute("member", member);
            }
        }
        return super.preHandle(request, response, handler);
    }
}
